package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.DLLInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class DLL_Test_Activity extends AppCompatActivity {
    private static final String TAG = "DLL_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;

    Button btn_DLL_Pass, btn_DLL_Fail, btn_DLL_All_OnOff;
    TextView tV_DLL1_Set, tV_DLL2_Set, tV_DLL3_Set, tV_DLL1_Status, tV_DLL2_Status, tV_DLL3_Status;
    SeekBar seekBar_DLL1, seekBar_DLL2, seekBar_DLL3;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;
    int rpm_now, dr_now;

    boolean is_DLL_All_On = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_dll_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        initCerebellumManager();
        seekBar_DLL1 = findViewById(R.id.seekBar_DLL1);
        seekBar_DLL2 = findViewById(R.id.seekBar_DLL2);
        seekBar_DLL3 = findViewById(R.id.seekBar_DLL3);
        tV_DLL1_Set = findViewById(R.id.tV_DLL1_Set);
        tV_DLL2_Set = findViewById(R.id.tV_DLL2_Set);
        tV_DLL3_Set = findViewById(R.id.tV_DLL3_Set);
        tV_DLL1_Status = findViewById(R.id.tV_DLL1_Status);
        tV_DLL2_Status = findViewById(R.id.tV_DLL2_Status);
        tV_DLL3_Status = findViewById(R.id.tV_DLL3_Status);

        Factory_DLL_SB(1, seekBar_DLL1, tV_DLL1_Set);//SeekBar And SetDLL
        Factory_DLL_SB(2, seekBar_DLL2, tV_DLL2_Set);//SeekBar And SetDLL
        Factory_DLL_SB(3, seekBar_DLL3, tV_DLL3_Set);//SeekBar And SetDLL
        Factory_DLL_BTN();
        Refresh_Status_Task_Init();
    }

    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }

    private void Factory_DLL_SB(int num, SeekBar seekBar, TextView textView){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int rpm_val = 0, direction = 1;
            String textView_str = "DLL"+num+":";
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                switch (progress){
                    case 1:{
                        direction = 0;
                        rpm_val = 8000;
                        break;
                    }
                    case 2:{
                        direction = 0;
                        rpm_val = 4320;
                        break;
                    }
                    case 3:{
                        direction = 0;
                        rpm_val = 0;
                        break;
                    }
                    case 4:{
                        direction = 1;
                        rpm_val = 0;
                        break;
                    }
                    case 5:{
                        direction = 1;
                        rpm_val = 4320;
                        break;
                    }
                    case 6:{
                        direction = 1;
                        rpm_val = 8000;
                        break;
                    }
                    default:
                        break;
                }
                if(direction == 1){
                    textView_str = "DLL"+num+":+"+rpm_val+"RPM";
                }else if(direction == 0){
                    textView_str = "DLL"+num+":-"+rpm_val+"RPM";
                }
                textView.setText(textView_str);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //Log.d(TAG, "Val:"+rpm_val);
                if(SetDLL(num, direction, rpm_val)){
                    Toast.makeText(DLL_Test_Activity.this, textView_str+"设定成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(DLL_Test_Activity.this, textView_str+"设定失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private boolean GetDLL(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            getter.getDLLInfo(num);
            dr_now = getter.getDLLInfo(num).getPower();
            rpm_now = getter.getDLLInfo(num).getRev();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private boolean SetDLL(int num, int direction, int rpm) throws ProtocolException {
        try {
            DLLInfo dllInfo = new DLLInfo();
            dllInfo.setOrder(num);
            dllInfo.setPower(direction);
            dllInfo.setRev(rpm);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setDLLInfo(dllInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private void Factory_DLL_BTN(){
        btn_DLL_Pass = findViewById(R.id.btn_DLL_Pass);
        btn_DLL_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("DLL","通过");
                if(editor.commit()){
                    Toast.makeText(DLL_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(DLL_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(DLL_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_DLL_Fail = findViewById(R.id.btn_DLL_Fail);
        btn_DLL_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("DLL","未通过");
                if(editor.commit()){
                    Toast.makeText(DLL_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(DLL_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(DLL_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_DLL_All_OnOff = findViewById(R.id.btn_DLL_All_OnOff);
        btn_DLL_All_OnOff.setText("设定所有动量轮：正向，6000 RPM");
        btn_DLL_All_OnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(is_DLL_All_On){
                    for(int i=1; i<4; i++){
                        SetDLL(i, 1, 0);
                    }
                    btn_DLL_All_OnOff.setText("设定所有动量轮：正向，6000 RPM");
                }else{
                    for(int i=1; i<4; i++){
                        SetDLL(i, 1, 6000);
                    }
                    btn_DLL_All_OnOff.setText("设定所有动量轮：正向，0 RPM");
                }
                is_DLL_All_On = !is_DLL_All_On;
            }
        });

    }
    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 2000);
                Refresh_DLL_Status(1, tV_DLL1_Status);
                Refresh_DLL_Status(2, tV_DLL2_Status);
                Refresh_DLL_Status(3, tV_DLL3_Status);
                //Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }
    private void Refresh_DLL_Status(Integer num, TextView tV){
        if(GetDLL(num)){
            String str_status = "DLL"+num+"当前转速:";
            if(dr_now == 1){
                str_status = "DLL"+num+"当前转速:+"+rpm_now;
            } else if (dr_now == 0) {
                str_status = "DLL"+num+"当前转速:-"+rpm_now;
            } else {
                str_status = "方向错误";
            }
            tV.setText(str_status);
        }else{
            tV.setText("获取失败");
        }
    }


    @Override
    public void onBackPressed() {
        Intent intent = new Intent(DLL_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(DLL_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}